<?php

namespace App\Common\Utils;

use Gregwar\Captcha\CaptchaBuilder;

class Captcha
{
    // 输出验证码图片
    public function output($name = 'default', $width = 200, $height = 80, $phrase = null)
    {
        $captcha = new CaptchaBuilder($phrase);

        header('Content-type: image/jpeg');
        $cap = $captcha->build($width, $height);
        $_SESSION['captcha_' . $name] = $cap->getPhrase();
        $cap->output();
        return null;
    }

    // 生成验证码到服务器
    public function save($name = 'default', $phrase = null)
    {
        $captcha = new CaptchaBuilder($phrase);
        $cap = $captcha->build(200, 80);
        $_SESSION['captcha_' . $name] = $cap->getPhrase();
        $cap->save(ROOT . '/storage/' . $name . '.jpeg');
        return null;
    }

    // 检查验证码
    public function checkCode($code, $name = 'default')
    {
        if (!isset($_SESSION['captcha_' . $name])) {
            return false;
        }
        return $_SESSION['captcha_' . $name] == $code;
    }
}
